package com.me.bbs.service.impl;

import com.me.bbs.entity.Comment;
import com.me.bbs.entity.CommentLike;
import com.me.bbs.entity.User;
import com.me.bbs.mapper.CommentLikeMapper;
import com.me.bbs.service.ICommentLikeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.me.bbs.service.ICommentService;
import com.me.bbs.service.IPostService;
import com.me.bbs.service.IUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lm
 * @since 2023-01-09
 */
@Service
public class CommentLikeServiceImpl extends ServiceImpl<CommentLikeMapper, CommentLike> implements ICommentLikeService {
    @Resource
    ICommentService commentService;
    @Resource
    IUserService userService;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void like(String commentId, Long userId) throws Exception {
        CommentLike one = this.lambdaQuery().eq(CommentLike::getCommentId, commentId)
                .eq(CommentLike::getUser, userId)
                .one();
        if(one != null) return;
        CommentLike commentLike = new CommentLike();
        Comment comment = commentService.getById(commentId);
        commentLike.setAuthor(comment.getAuthor());
        commentLike.setUser(userId);
        commentLike.setCommentId(comment.getCommentId());
        boolean save = this.save(commentLike);
        if(!save)
            throw new Exception("保存出错");
        commentService.lambdaUpdate()
                .eq(Comment::getCommentId,comment.getCommentId())
                .setSql("like_count = like_count + 1")
                .update();
        userService.lambdaUpdate()
                .eq(User::getUserId, userId)
                .setSql("like_count = like_count + 1")
                .update();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelLike(String commentId, Long userId) throws Exception {
        Comment comment = commentService.getById(commentId);
        boolean remove = this.lambdaUpdate()
                .eq(CommentLike::getUser, userId)
                .eq(CommentLike::getCommentId, comment.getCommentId())
                .remove();
        if(!remove)
            throw new Exception("删除出错");
        commentService.lambdaUpdate()
                .eq(Comment::getCommentId,comment.getCommentId())
                .setSql("like_count = like_count - 1")
                .update();
        userService.lambdaUpdate()
                .eq(User::getUserId, userId)
                .setSql("like_count = like_count - 1")
                .update();
    }
}
